import { createRouter, createWebHistory } from "vue-router";

import type { RouteRecordRaw } from "vue-router";

//配置路由
const routes: RouteRecordRaw[] = [
  {
    path: "/",
    redirect: "/login",
  },
  {
    path: "/home",
    name: "home",
    redirect: "/welcome",
    component: () => import("@/views/Home/index.vue"),
    meta: {
      auth: true,
    },
    children: [
      {
        path: "/welcome",
        component: () => import("@/views/Home/Welcome/index.vue"),
      },
      {
        path: "/users",
        name: "users",
        component: () => import("@/views/Home/Users/index.vue"),
      },
      {
        path: "/roles",
        name: "roles",
        component: () => import("@/views/Home/Rights/roles.vue"),
      },
    ],
  },
  {
    path: "/login",
    name: "login",
    component: () => import("@/views/Login/index.vue"),
  },
];

const router = createRouter({
  history: createWebHistory(import.meta.env.BASE_URL),
  routes,
});

router.beforeEach((to, from, next) => {
  console.log("to::", to);

  //返回flag是否为true,如果为true，代表页面鉴权
  const flag = to.matched.some((item) => {
    return item.meta.auth;
  });
  if (flag) {
    //获取token
    const token = localStorage.getItem("token");
    if (token) {
      next();
    } else {
      //重定向到登录页面
      next("/login");
    }
  } else {
    next();
  }
});

export default router;
